package com.cyh.ebptpubjar.common.ebptjasypt;

import com.ulisesbocchio.jasyptspringboot.EncryptablePropertyDetector;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * @ClassName:   EbptEncryptablePropertyDetector
 * @Description:
 * @Author:      cyh
 * @CreateDate:  2022/1/12 21:12
 */
@Component
public class EbptEncryptablePropertyDetector  implements EncryptablePropertyDetector {
    //自定义的加入值，也就是 application.properties 里 value 的前缀
    public static final String ENCODED_PASSWORD_HINT = "EBPT@";
    @Override
    public boolean isEncrypted(String value) {
        if (null != value) {
            return value.startsWith(ENCODED_PASSWORD_HINT);
        }
        return false;
    }

    @Override
    public String unwrapEncryptedValue(String value) {
        return value.substring(ENCODED_PASSWORD_HINT.length());
    }

    @Bean("jasyptStringEncryptor")
    public StringEncryptor stringEncryptor() {
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        // 加密盐
        config.setPassword("salt");
        // 加密算法
        config.setAlgorithm("PBEWITHHMACSHA512ANDAES_256");
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName("SunJCE");
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
        config.setStringOutputType("base64");
        encryptor.setConfig(config);
        return encryptor;
    }
}
